package com.sunny.ynhz.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sunny.ynhz.R;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.api.okhttp.OkHttpHelper;
import com.sunny.ynhz.ui.base.AppBaseNoTranslationTitleBarActivity;
import com.sunny.ynhz.ui.message.ViewGroupUserActivity;
import com.sunny.ynhz.utils.AppManager;
import com.sunny.ynhz.utils.ShowUtils;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

public class ChatActivity extends AppBaseNoTranslationTitleBarActivity {
    private RequestQueue mQueue;
    private TextView viewUser;
    private String conversationType = "";//会话类型
    private TextView onlineText;
    private String title;
    private String userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        mQueue = Volley.newRequestQueue(this);
        Intent intent = getIntent();
        int type = intent.getIntExtra("type", -1);
            title = getIntent().getData().getQueryParameter("title");
            userid = getIntent().getData().getQueryParameter("targetId");
            Conversation.ConversationType mConversationType = Conversation.ConversationType.valueOf(getIntent().getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
            conversationType = mConversationType.getName();

        if (title.length() > 15) {
            title = title.substring(0, 15) + "...";
        }
        setTitle(title);
        setTitleSize(13);

        if (conversationType.equals("private")) {
            setLook("查看");
            findViewById(R.id.tv_look).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showuserinfo(userid, ChatActivity.this);
                }
            });
            checkOnline(userid);
        } else {
            //群
            setLook("成员");
            findViewById(R.id.tv_look).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ChatActivity.this, ViewGroupUserActivity.class);
                    intent.putExtra("gid", userid);
                    startActivity(intent);
                }
            });
            setOnline(false);
        }
        fullData();


    }

    public void fullData() {
        RongIM.getInstance().setGroupMembersProvider(new RongIM.IGroupMembersProvider() {
            @Override
            public void getGroupMembers(String s, RongIM.IGroupMemberCallback iGroupMemberCallback) {
                String url = NetUrl.baseUrl + "rong/web/getUserByGroupId?groupId=" + s + "&page=" + 1 + "&pageSize=10000";
                OkHttpHelper.getAsyn(ChatActivity.this, url, new OkHttpHelper.ResultCallback<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            ShowUtils.dismissProgress();
                            List<UserInfo> mlist = new ArrayList<>();
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray result = jsonObject.getJSONArray("result");
                            for (int i = 0; i < result.length(); i++) {
                                JSONObject jsonObject1 = result.getJSONObject(i);
                                String name = jsonObject1.getString("name");
                                String id = jsonObject1.getString("id");
                                UserInfo userInfo = new UserInfo(id, name, null);
                                mlist.add(userInfo);
                            }
                            iGroupMemberCallback.onGetGroupMembersResult(mlist);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AppManager.getInstance().finishActivity(LoadActivity.class);
                            }
                        }, 3000);


                    }

                    @Override
                    public void onError(okhttp3.Request request, Exception e) {
                        super.onError(request, e);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AppManager.getInstance().finishActivity(LoadActivity.class);
                            }
                        }, 3000);
                    }

                    @Override
                    public void onBefore(okhttp3.Request request) {
                        super.onBefore(request);
                        doAcitivity(LoadActivity.class);

                    }
                });

            }
        });


    }


    private void checkOnline(String userid) {
        String url = NetUrl.baseUrl + "rong/web/checkOnline?userId=" + userid;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                String status = jsonObject.getString("status");
                if (status.equals("1")) {
                    setOnline(true);
                } else {
                    setOnline(false);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }, error -> {

        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("uid", "");
                return hashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    private void showuserinfo(final String userid, final Context context) {
        String url = NetUrl.baseUrl + "sysUserB/getAppUserByUserId?userId=" + userid;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject info = jsonObject.getJSONObject("user");
                    String name = info.getString("name");
                    String mobile = info.getString("mobile");
                    String job = info.getString("job");
                    String rivertype = info.getString("rivertype");
                    String address = info.getString("city") + info.getString("area") + info.getString("town") + info.getString("village");
                    AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);

                    builder.setMessage("姓名：" + name + "\n电话：" + mobile + "\n区域：" + address + "\n用户类别：" + rivertype + "\n职务:" + job);
                    builder.setPositiveButton("关闭", null);
                    builder.create().show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mQueue.add(stringRequest);
    }

}
